using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.UI.Xaml.Controls;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

namespace WinUITest.Pages
{
    [Menu("树懒加载")]
    public sealed partial class TreeLazyLoadingPage : Page
    {
        public TreeLazyLoadingViewModel ViewModel { get; } = new();
        public TreeLazyLoadingPage() => InitializeComponent();

        private async void TreeView_Expanding(TreeView sender, TreeViewExpandingEventArgs args)
        {
            if (args.Item is not TreeDataViewModel item || item.Children.Count > 0) return;
            item.ExpandedGlyph = "\uE712";
            await Task.Delay(1000);
            for (int i = 0; i < 3; i++)
            {
                item.Children.Add(new TreeDataViewModel() { Name = $"{item.Name}-{i}", Level = item.Level + 1 });
            }
            item.ExpandedGlyph = "\uE70D";
        }
    }
    public class TreeLazyLoadingViewModel : ObservableObject
    {
        public ObservableCollection<TreeDataViewModel> DataSource { get; } = [];
        public TreeLazyLoadingViewModel()
        {
            for (int i = 0; i < 3; i++)
            {
                DataSource.Add(new TreeDataViewModel() { Name = i.ToString(), Level = 0 });
            }
        }
    }
    public partial class TreeDataViewModel : ObservableObject
    {
        [ObservableProperty]
        public partial string Name { get; set; } = string.Empty;
        public int Level { get; set; } = 0;
        [ObservableProperty]
        public partial string ExpandedGlyph { get; set; } = "\uE70D";
        public ObservableCollection<TreeDataViewModel> Children { get; } = [];
    }
}
